﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using CleanLite.DynamicApi;
using CleanLite.Infrastructure;
using CleanLite.Shared.Configuration;
using CleanLite.Web.Dynamic;
using CleanLite.Web.Filters;
using CleanLite.Web.Module;

namespace CleanLite.Web
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            //初始化IConfiguration 配置服务[静态文件配置,全局可使用]
            ConfigurationService.Initialize(builder.Configuration);

            //使用Autofac作为DI容器
            builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
            builder.Host.ConfigureContainer<ContainerBuilder>(c =>
            {
                c.RegisterModule(new AutofacModule());
            });
            builder.Services.AddEndpointsApiExplorer();
            //注入程序以外的服务[所有服务在此可查找/建议新增服务在此处新增]
            builder.Services.AddHostServices();
            builder.Services.AddControllers(options =>
            {
                options.Filters.Add<GlobalApiResponseFilter>();
                options.Filters.Add<GlobalExceptionFilter>();
            });
            //注入动态API服务[DefaultCustomControllerFeatureProvider是默认提供的控制器识别策略]
            builder.Services.AddDynamicApi(options =>
            {
                options.CustomControllerFeatureProvider = new CustomControllerFeatureProvider();//追加自定义控制器识别策略
                options.IgnoreMethodSuffix.AddRange(ConfigurationService.GetStringList("IgnoreMethodSuffix"));//追加方法名后缀忽略规则
                options.IgnoreControllerSuffix.AddRange(ConfigurationService.GetStringList("IgnoreControllerSuffix"));//追加控制器后缀忽略规则
                options.ApiPrefix = "";//接口前缀
            });

            var app = builder.Build();

            //使用动态API中间件,注册指定的程序集
            app.UseDynamicApi();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.MapControllers();
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }
            app.Run();
        }
    }
}